import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import getMeanuRoutes from '@/utils/permission';
import Home from '../views/Layout/Home.vue';
import Login from '../views/Layout/Login.vue';

Vue.use(VueRouter);

// 异步路由数组 左侧
const aysncRouterMap = [{
  // 商品
  path: '/product',
  name: 'Product',
  meta: {
    title: '商品',
    icon: 'inbox',
    hidden: false,
  },
  component: Home,
  children: [{
    path: 'list',
    name: 'Productlist',
    meta: {
      title: '商品列表',
      icon: 'unordered-list',
      hidden: false,
    },
    component: () => import('@/views/page/productlist.vue'),
  }, {
    path: 'add',
    name: 'Productadd',
    meta: {
      title: '添加商品',
      icon: 'file-add',
      hidden: false,
    },
    component: () => import('@/views/page/productAdd.vue'),
  }, {
    path: 'edit/:id',
    name: 'ProductEdit',
    meta: {
      title: '编辑商品',
      icon: 'file-add',
      hidden: true,
    },
    component: () => import('@/views/page/productAdd.vue'),
  }, {
    path: 'category',
    name: 'Category',
    meta: {
      title: '类目管理',
      icon: 'project',
      hidden: false,
    },
    component: () => import('@/views/page/category.vue'),
  }],
}];

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: 'Index',
    // 导航名字
    meta: {
      title: '首页',
      hidden: false,
      icon: 'home',
    },
    children: [{
      path: '/index',
      name: 'Index',
      meta: {
        title: '统计',
        icon: 'number',
        hidden: false,
      },
      // 路由懒加载
      component: () => import('@/views/page/index.vue'),
    }],
  }, {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录',
      hidden: true,
    },
    component: Login,
  },
];

const router = new VueRouter({
  routes,
});

// 判断是否已经添加过路由 添加过则不需要重复添加
let isAddRoutes = false;
// 路由守卫(路由拦截)
router.beforeEach((to, from, next) => {
  // 如果去的路径不是登录状态
  if (to.path !== '/login') {
    if (store.state.user.appkey && store.state.user.username && store.state.user.role) {
      if (!isAddRoutes) {
        // 过滤权限
        const menuRoutes = getMeanuRoutes(store.state.user.role, aysncRouterMap);
        // 添加筛选路由到路由中
        router.addRoutes(menuRoutes);
        // 拼接路由
        store.dispatch('changeMenuRoutes', routes.concat(menuRoutes)).then(() => {
          router.addRoutes(menuRoutes);
          next();
        });
        isAddRoutes = true;
      }
      // 如果有则继续进入页面
      next();
    } else {
      // 如果没有则跳转到登录页面
      next('/login');
    }
  }
  return next();
});

export default router;
